var mysql = require('mysql');
var pool = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "158647",
  database: "adminbase",
  multipleStatements: true //多个语句
})

function getTime() {
  var date = new Date();
  var seperator1 = "-";
  var seperator2 = ":";
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + " " + date.getHours() + seperator2 + date.getMinutes() + seperator2 + date.getSeconds();
  return currentdate;
}

let queryFun = function (sql, arr, callback) {
  pool.getConnection(function (err, connection) {
    if (err) throw err;
    connection.query(sql, arr, function (error, resultes) {
      // 释放链接返回连接池，准备由其他人重复使用
      connection.release();
      if (error) throw error;
      // 执行回调函数，将数据返回
      callback && callback(resultes);
    })
  })
}

let query = function (sql, arr = [], callback) {
  if(typeof callback == "function") queryFun(sql, arr, callback)
  else return new Promise((resolve) => queryFun(sql, arr, resolve))
}

module.exports = {
  pool,
  getTime,
  query
}